package com.changgou.oauth.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.oauth.service.AuthService;
import com.changgou.oauth.util.AuthToken;
import com.changgou.oauth.util.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletResponse;
import javax.swing.plaf.PanelUI;

@Controller
@RequestMapping("/oauth")
public class AuthController {
    @Autowired
    AuthService authService;

    @Value("${auth.clientSecret}")
    private String clientSecret;
    @Value("${auth.clientId}")
    private String clientId;
    @Value("${auth.cookieDomain}")
    private String cookieDomain;
    @Value("${auth.cookieMaxAge}")
    private String cookieMaxAge;
@RequestMapping("toLogin")
    public String toLogin(){
    return "login";
}



    @RequestMapping("/login")
    @ResponseBody
    public Result login(String username, String password, HttpServletResponse response){
        if ( StringUtils.isEmpty (username) ) {
            throw new RuntimeException ("请输入用户名");
        }
            if ( StringUtils.isEmpty (password) ) {
            throw new RuntimeException ("请输入用户密码");
        }

        AuthToken authToken = authService.login (username,password,clientId,clientSecret);


        //authToken存入cookie中
        this.saveJtiToCookie (authToken.getJti (), response);
return new Result (true, StatusCode.OK,"登入成功",authToken.getJti ());
    }

    private void saveJtiToCookie(String jti, HttpServletResponse request) {
        CookieUtil.addCookie (request, cookieDomain, "/", "uid", jti, cookieMaxAge, false);
    }


}
